//
//  CTLoginLogic.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/22.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTLoginLogic.h"
#import "CTDebugManager.h"
#import "CTRequestUtil.h"
#import "CTUrl.h"
#import "CTTextManager.h"
#import "CTAppLanguage.h"
#import <ShareSDK/ShareSDK.h>
#import <QZoneConnection/ISSQZoneApp.h>
#import "WXApi.h"
#import "WeiboSDK.h"
#import <TencentOpenAPI/QQApi.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

#import "CRSA.h"
#import "CTHeader.h"
#import "CTDeviceFunction.h"
#import "CTAppLanguage.h"
#import "CTFile.h"
#import "CTGenRequestData.h"
#import "CTRequestErrorCode.h"

@interface CTLoginLogic ()
{
    CTTpLoginType loginType;
    
    NSString * userPhoneNumber;
}

@end

@implementation CTLoginLogic

@synthesize delegate;

- (void)dealloc
{
    userPhoneNumber = nil;
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTLoginLogic Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}



-(void)mobileLoginRequest:(CTMobileLoginRequestItem *)item
 successCompletionHandler:(requestSuccessBlock)successBlock
            failedHandler:(requestFailedBlock)failedBlock
{
    userPhoneNumber = item.mobile;
    
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        [param setObject:item.mobile forKey:@"mobile"];
        [param setObject:item.cipher forKey:@"cipher"];
        [param setObject:item.deviceid forKey:@"deviceid"];
        [param setObject:item.openid forKey:@"openid"];
        [param setObject:item.clienttime forKey:@"clienttime"];
        
    }
    @catch (NSException *exception) {
        
    }
   
    [CTRequestUtil sendAsyPostRequest:CT_URL_ACCOUNTS_LOGIN(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
      
        BOOL isParserSuccess = [self parserMobileLoginData:data];
        if (isParserSuccess == YES) {
            
            [CTFile removeFile:@"homepage" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
            [CTFile removeFile:@"discovery" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
            [CTFile removeFile:@"user" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginSuccessNotification object:nil];
            successBlock();
        }
        else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
            failedBlock();
        }
        
        
    } withFailedHandler:^(NSError *error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
        failedBlock();
    }];
}



-(void)tpLoginRequestWithLoginType:(CTTpLoginType)type

{
 
    ShareType shareType;
    loginType = type;
    NSString * url ;
    switch (loginType) {
        case CTTpLoginTypeQQ:
            url = CT_URL_ACCOUNTS_QQ(version);
            shareType = ShareTypeQQSpace;
            break;
        case CTTpLoginTypeWechat:
            url = CT_URL_ACCOUNTS_WECHAT(version);
            shareType = ShareTypeWeixiSession;
            break;
        case CTTpLoginTypeWeiBo:
            url = CT_URL_ACCOUNTS_WEIBO(version);
            shareType = ShareTypeSinaWeibo;
            break;
        default:
            break;
    }
   
    [ShareSDK getCredentialWithType:shareType];
    [ShareSDK getUserInfoWithType:shareType
                      authOptions:nil
                           result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error)
     {
         if (error != nil) {
             [CTDebugManager showErrorLogInfo:[error errorDescription]];
             if ([self.delegate respondsToSelector:@selector(authorFailed:)]) {
                 [self.delegate authorFailed:self];
             }
         }
         if (result == YES) {
             
             NSDictionary * dic = [userInfo sourceData];
             
             NSInteger login_type = 1;
             switch (type) {
                 case CTTpLoginTypeWeiBo:
                     login_type = 1;
                     break;
                 case CTTpLoginTypeQQ:
                     login_type = 2;
                     break;
                 case CTTpLoginTypeWechat:
                     login_type = 3;
                     break;
                 default:
                     break;
             }
            CTThirdPartyLoginRequestItem* thirdPartyLoginRequestItem = [CTGenRequestData genTPItemInfo:dic withType:login_type];
//             CTThirdPartyLoginRequestItem* item = [[CTThirdPartyLoginRequestItem alloc] init];
//             CTThirdPartyLoginRequestItem* thirdPartyLoginRequestItem = [self genTPItem:item withInfo:dic];
             
             NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
             @try {
                 
                 [param setObject:thirdPartyLoginRequestItem.deviceid forKey:@"deviceid"];
                 [param setObject:thirdPartyLoginRequestItem.openid forKey:@"openid"];
                 [param setObject:thirdPartyLoginRequestItem.clienttime forKey:@"clienttime"];
                 [param setObject:thirdPartyLoginRequestItem.channel forKey:@"channel"];
                 [param setObject:thirdPartyLoginRequestItem.identification forKey:@"identification"];
                 [param setObject:thirdPartyLoginRequestItem.name forKey:@"name"];
                 [param setObject:thirdPartyLoginRequestItem.head forKey:@"head"];
                 [param setObject:thirdPartyLoginRequestItem.lang forKey:@"lang"];
                 
             }
             @catch (NSException *exception) {
                 [CTDebugManager showErrorLogInfo:@"第三方登录请求参数转换字典失败！！"];
             }
             
             [CTRequestUtil sendAsyPostRequest:url withParam:param withCompletionSuccessHandler:^(NSData *data) {
               
                 
                 BOOL isParserSuccess = [self parserTPLoginData:data];
                 if (isParserSuccess == YES) {
                     
                     [CTFile removeFile:@"homepage" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                     [CTFile removeFile:@"discovery" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                     [CTFile removeFile:@"user" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                     
                     [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginSuccessNotification object:nil];
                     
                     if ([self.delegate respondsToSelector:@selector(tpLoginSuccessed:)]) {
                         [self.delegate tpLoginSuccessed:self];
                     }
                 }
                 else
                 {
                     NSError *error;
                     
                     [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
                     
                     if ([self.delegate respondsToSelector:@selector(tpLoginFailed:withError:)]) {
                         [self.delegate tpLoginFailed:self withError:error];
                     }
                 }
                 
             } withFailedHandler:^(NSError *error) {
                 
                 [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
                 
                 if ([self.delegate respondsToSelector:@selector(tpLoginFailed:withError:)]) {
                     [self.delegate tpLoginFailed:self withError:error];
                 }
             }];
             
             
             
         }
         else
         {
            [CTDebugManager showErrorLogInfo:[error errorDescription]];
             if ([self.delegate respondsToSelector:@selector(authorFailed:)]) {
                 [self.delegate authorFailed:self];
             }
         }
         
     }];
}






#pragma mark - data parser -

-(BOOL)parserMobileLoginData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                  
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    NSString * tokenStr = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"token"]];
                    NSDictionary * userInfoDic = [infoDic objectForKey:@"user"];
                    
                    //存入文件
                    
                    //token:
                    [CTFile cacheFile:tokenStr
                             fileName:@"token.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    //user phonenumber
                    [CTFile cacheFile:userPhoneNumber
                             fileName:@"userPhoneNumber.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    //user info
                    [CTFile cacheDicFile:[userInfoDic mutableCopy]
                                fileName:@"userInfo.plist"
                                 saveDoc:CTFileDocDocuments
                                savePath:@"user"];
                    
                }else {
                    
                    NSString * errDescription = [CTRequestErrorCode errDescription:errCode];
                    [CTDebugManager showErrorLogInfo:errDescription];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析手机号登陆数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析手机号登陆数据错误！"];
    }
    
    return isParserSuccess;

}


-(BOOL)parserTPLoginData:(NSData *)resultData
{
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
         
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    NSDictionary * userInfoDic = [infoDic objectForKey:@"user"];
                    NSString * tokenStr = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"token"]];
                    NSString * typeStr = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"type"]];
                   
                    //存入文件
                    
                    //token:
                    [CTFile cacheFile:tokenStr
                             fileName:@"token.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    //user type
                    [CTFile cacheFile:typeStr
                             fileName:@"userType.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    //user info
                    [CTFile cacheDicFile:[userInfoDic mutableCopy]
                                fileName:@"userInfo.plist"
                                 saveDoc:CTFileDocDocuments
                                savePath:@"user"];
                    
                }else {
                    NSString * errDescription = [CTRequestErrorCode errDescription:errCode];
                    [CTDebugManager showErrorLogInfo:errDescription];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析手机号登陆数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析手机号登陆数据错误！"];
    }
    
    return isParserSuccess;
}



#pragma mark - 组装item -

-(CTThirdPartyLoginRequestItem *)genTPItem:(CTThirdPartyLoginRequestItem *)itm withInfo:(NSDictionary *)info
{
    @try {
        NSString * languageStr = [CTAppLanguage systemLanguage];
        itm.openid = [[CRSA shareInstance] encryptByRsa:[CTDeviceFunction DeviceUDID] withKeyType:KeyTypePublic];
        itm.deviceid = [CTDeviceFunction DeviceUDID];
        itm.clienttime = [CTDeviceFunction UnixTimestamp];
        if ([languageStr isEqualToString:@"zh-Hans"])itm.lang = @"cn";
        else itm.lang = @"en";
        itm.channel = @"appStore";
        
        
        switch (loginType) {
            case CTTpLoginTypeQQ:
                itm.identification = [NSString stringWithFormat:@"%@",[info objectForKey:@"uid"]];
                itm.name = [NSString stringWithFormat:@"%@",[info objectForKey:@"nickname"]];
                itm.head = [NSString stringWithFormat:@"%@",[info objectForKey:@"figureurl_qq_2"]];
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"gender"]] isEqualToString:@"男"]) {
                    itm.gender = @"1";
                }else if([[NSString stringWithFormat:@"%@",[info objectForKey:@"gender"]] isEqualToString:@"女"]){
                    itm.gender = @"2";
                }else{
                    itm.gender = @"0";
                }
                break;
            case CTTpLoginTypeWechat:
                itm.identification = [NSString stringWithFormat:@"%@",[info objectForKey:@"unionid"]];
                itm.name = [NSString stringWithFormat:@"%@",[info objectForKey:@"nickname"]];
                itm.head = [NSString stringWithFormat:@"%@",[info objectForKey:@"headimgurl"]];
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"sex"]] isEqualToString:@"1"]) {
                    itm.gender = @"1";
                }else if([[NSString stringWithFormat:@"%@",[info objectForKey:@"sex"]] isEqualToString:@"2"]){
                    itm.gender = @"2";
                }else{
                    itm.gender = @"0";
                }
                break;
            case CTTpLoginTypeWeiBo:
                itm.identification = [NSString stringWithFormat:@"%@",[info objectForKey:@"idstr"]];
                itm.name = [NSString stringWithFormat:@"%@",[info objectForKey:@"name"]];
                itm.head = [NSString stringWithFormat:@"%@",[info objectForKey:@"avatar_large"]];
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"gender"]] isEqualToString:@"m"]) {
                    itm.gender = @"1";
                }else if([[NSString stringWithFormat:@"%@",[info objectForKey:@"gender"]] isEqualToString:@"f"]){
                    itm.gender = @"2";
                }else{
                    itm.gender = @"0";
                }

                break;
            default:
                break;
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析第三方授权数据失败！！"];
    }
   
   
    return itm;
}



#pragma mark - 用户名 手机号 密码 匹配 -

-(BOOL)isPasswordEnable:(NSString *)pass
{
    
    if (pass.length < 6 || pass.length > 14) {
        if ([self.delegate respondsToSelector:@selector(isPassWordEnable:description:)]) {
            [self.delegate isPassWordEnable:NO description:[CTAppLanguage localizedStringForKey:@"logInView_PasswordDescription_a" withValue:nil withTable:@"Language"]];
        }
        
        return NO;
    }
    
    if ([[CTTextManager shareInstance] isMatch:pass] == NO) {
        if ([self.delegate respondsToSelector:@selector(isPassWordEnable:description:)]) {
            [self.delegate isPassWordEnable:NO description:[CTAppLanguage localizedStringForKey:@"logInView_PasswordDescription_b" withValue:nil withTable:@"Language"]];
        }
        
        return NO;
    }
    
    return YES;
}


@end
